<template>
  <div class="detection-container">
    <!-- 顶部导航栏 -->
    <el-header class="app-header">
      <div class="logo">
        <img src="@/assets/logo.png" alt="Logo" class="logo-image">
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="main-content">
      <!-- 模型选择卡片 -->
      <el-card class="model-select-card" shadow="never" v-if="!selectedModel">
        <template #header>
          <div class="section-header">
            <el-icon :size="18" color="#4caf50"><Select /></el-icon>
            <span class="section-title">选择识别模型</span>
          </div>
        </template>

        <el-row :gutter="20">
          <!-- 消费者模型选项 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-if="userRole === 'consumer'">
            <el-card shadow="hover" class="model-card" @click="selectModel('fruit')">
              <div class="model-content">
                <div class="model-icon">🍎</div>
                <h3>果实识别模型</h3>
                <p>监测果实成熟度和健康状况</p>
              </div>
            </el-card>
          </el-col>

          <!-- 农民模型选项 -->
          <template v-if="userRole === 'farmer'">
            <el-col :xs="12" :sm="8" :md="6" :lg="6">
              <el-card shadow="hover" class="model-card" @click="selectModel('seed')">
                <div class="model-content">
                  <div class="model-icon">🌱</div>
                  <h3>种子识别模型</h3>
                  <p>识别种子品质和种类</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6" :lg="6">
              <el-card shadow="hover" class="model-card" @click="selectModel('growth')">
                <div class="model-content">
                  <div class="model-icon">🌿</div>
                  <h3>生长阶段识别</h3>
                  <p>判断作物生长阶段</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6" :lg="6">
              <el-card shadow="hover" class="model-card" @click="selectModel('leaf')">
                <div class="model-content">
                  <div class="model-icon">🍃</div>
                  <h3>叶片识别模型</h3>
                  <p>诊断叶片疾病和健康状况</p>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="12" :sm="8" :md="6" :lg="6">
              <el-card shadow="hover" class="model-card" @click="selectModel('fruit')">
                <div class="model-content">
                  <div class="model-icon">🍎</div>
                  <h3>果实识别模型</h3>
                  <p>监测果实成熟度和健康状况</p>
                </div>
              </el-card>
            </el-col>
          </template>
        </el-row>
      </el-card>

      <!-- 图像处理区域 -->
      <el-card class="image-process-card" shadow="never" v-else>
        <template #header>
          <div class="section-header">
            <el-icon :size="18" color="#4caf50"><Camera /></el-icon>
            <span class="section-title">{{ modelNames[selectedModel] }}</span>
            <el-button type="text" @click="backToModelSelect" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>
              更换模型
            </el-button>
          </div>
        </template>

        <!-- 图片展示区域 -->
        <div class="image-container">
          <el-empty v-if="!imageSrc" description="请上传图片" :image-size="100">
            <template #image>
              <el-icon :size="60" color="#dcdfe6"><Picture /></el-icon>
            </template>
          </el-empty>

          <el-image
              v-else
              :src="imageSrc"
              fit="cover"
              class="uploaded-image"
              :preview-src-list="[imageSrc]"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
              </div>
            </template>
          </el-image>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
              type="primary"
              plain
              @click="showUploadOptions"
              class="upload-btn"
          >
            <el-icon><Upload /></el-icon>
            上传图片
          </el-button>

          <el-button
              type="success"
              :disabled="!imageSrc"
              @click="processWithYOLO"
          >
            <el-icon><Aim /></el-icon>
            YOLO识别
          </el-button>
        </div>

        <!-- 快捷操作 -->
        <div class="quick-actions">
          <el-button type="text" @click="goToGallery">
            <el-icon><Notebook /></el-icon>
            查看图鉴
          </el-button>
          <el-button type="text" @click="goToHistory">
            <el-icon><Clock /></el-icon>
            历史记录
          </el-button>
        </div>
      </el-card>

      <!-- 上传选项对话框 -->
      <el-dialog
          v-model="showOptions"
          title="选择上传方式"
          width="80%"
          :show-close="false"
          custom-class="upload-dialog"
      >
        <div class="upload-options">
          <el-button
              type="primary"
              @click="takePhoto"
              class="option-btn"
          >
            <el-icon><CameraFilled /></el-icon>
            拍照上传
          </el-button>
          <el-button
              type="success"
              @click="chooseFromGallery"
              class="option-btn"
          >
            <el-icon><Picture /></el-icon>
            从相册选择
          </el-button>
        </div>
        <template #footer>
          <el-button @click="hideUploadOptions" plain>取消</el-button>
        </template>
      </el-dialog>

      <!-- 处理中遮罩 -->
      <el-dialog
          v-model="processing"
          :show-close="false"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="auto"
          custom-class="processing-dialog"
      >
        <div class="processing-content">
          <el-icon class="is-loading" :size="40" color="#4caf50"><Loading /></el-icon>
          <p>处理中，请稍候...</p>
        </div>
      </el-dialog>
    </el-main>

    <!-- 底部导航栏 -->
    <el-footer class="bottom-nav">
      <el-menu
          mode="horizontal"
          :default-active="activeIndex"
          class="nav-menu"
          @select="handleMenuSelect"
          active-text-color="#4caf50"
          :ellipsis="false"
      >
        <el-menu-item index="/home">
          <template #title>
            <el-icon :size="24"><HomeFilled /></el-icon>
            <span>首页</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/detection">
          <template #title>
            <el-icon :size="24"><Camera /></el-icon>
            <span>识别</span>
          </template>
        </el-menu-item>
        <el-menu-item index="/gallery">
          <template #title>
            <el-icon :size="24"><Notebook /></el-icon>
            <span>图鉴</span>
          </template>
        </el-menu-item>
      </el-menu>
    </el-footer>
  </div>
</template>

<script>
import {
  Select,Aim,
  Camera, Upload, Notebook, Clock,
  Picture, CameraFilled, Loading, ArrowLeft, HomeFilled
} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

export default {
  name: 'DetectionPage',
  components: {
    HomeFilled,Aim,
    Select,
    Camera, Upload, Notebook, Clock,
    Picture, CameraFilled, Loading, ArrowLeft
  },
  data() {
    return {
      imageSrc: '',
      showOptions: false,
      processing: false,
      selectedModel: '',
      userRole: '',
      modelNames: {
        'seed': '种子识别',
        'growth': '生长阶段识别',
        'leaf': '叶片识别',
        'fruit': '果实识别',
      },
      modelFeature: {
        'fruit': 4,
        'seed': 1,
        'leaf': 3,
        'growth': 2
      },
      selectedFeatureId: 0,
      predictions: [],
      advice: ''
    }
  },
  computed: {
    activeIndex() {
      return this.$route.path
    }
  },
  created() {
    this.userRole = localStorage.getItem('role') || ''
    this.selectedModel = ''
    if (this.selectedModel) {
      this.selectedFeatureId = this.modelFeature[this.selectedModel]
    }
  },
  methods: {
    selectModel(modelType) {
      if(modelType==='seed'||modelType==='growth'){
        ElMessage.warning("模型待开发！")
        return
      }
      this.selectedModel = modelType
      this.selectedFeatureId = this.modelFeature[modelType]
    },
    backToModelSelect() {
      this.selectedModel = ''
      this.imageSrc = ''
    },
    showUploadOptions() {
      this.showOptions = true
    },
    hideUploadOptions() {
      this.showOptions = false
    },
    takePhoto() {
      this.hideUploadOptions()
      this.simulateFileInput(true)
    },
    chooseFromGallery() {
      this.hideUploadOptions()
      this.simulateFileInput(false)
    },
    simulateFileInput(isCamera) {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'

      if (isCamera) {
        input.capture = 'camera'
      }

      input.onchange = (e) => {
        const file = e.target.files  [0]
        if (file) {
          this.displayImage(file)
        }
      }

      input.click()
    },
    displayImage(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageSrc = e.target.result
      }
      reader.readAsDataURL(file)
    },
    async processWithYOLO() {
      if (!this.imageSrc) {
        this.$message.warning('请先上传图片')
        return
      }

      this.processing = true
      try {
        const blob = await fetch(this.imageSrc).then(res => res.blob())
        const formData = new FormData()
        formData.append('file', blob, 'image.jpg')

        const token = localStorage.getItem('token')
        const user_id = localStorage.getItem('userId')
        const feature_id = this.selectedFeatureId

        if (!token || !user_id || !feature_id) {
          throw new Error('缺少必要的认证信息')
        }

        const url = new URL('http://47.120.40.5:5000/api/detection')
        url.searchParams.append('user_id', user_id)
        url.searchParams.append('feature_id', feature_id)
        url.searchParams.append('method_name', 'yolo')

        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Authorization': token
          },
          body: formData
        })

        if (response.status !== 200) {
          const errorData = await response.json()
          throw new Error(errorData.message || 'API请求失败')
        }

        const data = await response.json()
        if (data.status !== 'success') {
          throw new Error('检测失败')
        }

        this.imageSrc = 'data:image/jpeg;base64,' + data.result.image_64
        this.predictions = data.result.predictions
        this.advice = data.result.advice

        this.$router.push({
          path: '/RecognitionResults',
          query: {
            algorithm: 'YOLO',
            resultImg: this.imageSrc,
            predictions: encodeURIComponent(JSON.stringify(this.predictions)),
            advice: encodeURIComponent(JSON.stringify(this.advice))
          }
        })
      } catch (error) {
        console.error('处理图片时出错:', error)
        this.$message.error(error.message || '处理图片时出错')
      } finally {
        this.processing = false
      }
    },
    goToGallery() {
      this.$router.push('/gallery')
    },
    goToHistory() {
      this.$router.push('/history')
    },
    handleMenuSelect(index) {
      this.$router.push(index)
    }
  }
}
</script>

<style scoped>
.detection-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8faf8;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 顶部导航栏 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.logo-image {
  height: 40px;
  border-radius: 40px;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  padding: 15px 15px 70px;
  overflow-y: auto;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 卡片样式 */
.model-select-card,
.image-process-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

/* 分区标题 */
.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.back-btn {
  position: absolute;
  right: 0;
  color: #4caf50;
}

/* 模型卡片 */
.model-card {
  margin-bottom: 12px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s;
  height: 100%;
}

.model-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.2);
}

.model-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 10px;
  text-align: center;
}

.model-content h3 {
  font-size: 16px;
  color: #333;
  margin: 12px 0 8px;
}

.model-content p {
  font-size: 12px;
  color: #888;
  margin: 0;
}

/* 图像容器 */
.image-container {
  width: 100%;
  min-height: 300px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  overflow: hidden;
  border: 1px dashed #dcdfe6;
}

.uploaded-image {
  max-width: 100%;
  max-height: 400px;
  width: auto;
  height: auto;
  border-radius: 8px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #c0c4cc;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 20px;
}

.upload-btn {
  background-color: #e8f5e9;
  border-color: #4caf50;
  color: #4caf50;
}

.quick-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 10px;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0;
  height: 64px;
  background-color: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 1000;
}

.nav-menu {
  display: flex;
  justify-content: space-around;
  border: none;
  height: 100%;
}

.nav-menu :deep(.el-menu-item) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 64px;
  padding: 0;
  border-bottom: none;
  transition: all 0.3s;
}

.nav-menu :deep(.el-menu-item.is-active) {
  color: #4caf50 !important;
  background-color: #e8f5e9 !important;
}

.nav-menu :deep(.el-menu-item .el-icon) {
  margin-right: 0;
  margin-bottom: 6px;
  font-size: 20px;
}

/* 1. 模型卡片间距调整 */
.model-select-card {
  border-radius: 12px;
}

.model-card {
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.2s;
  height: 95%;
}

/* 2. 操作按钮改为上下排列 */
.action-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.action-buttons .el-button {
  width: 100%;
  max-width: 300px;
  height: 44px;
  display: flex;
  margin: 0;
  align-items: center;
  justify-content: center;
}
/* 3. 快捷操作样式调整 */
.quick-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.quick-actions .el-button {
  color: #4caf50;
  padding: 8px 16px;
  border-radius: 20px;
  background-color: rgba(76, 175, 80, 0.1);
  transition: all 0.3s;
  margin:0px;
}

.quick-actions .el-button:hover {
  background-color: rgba(76, 175, 80, 0.2);
}

.quick-actions .el-icon {
  margin-right: 8px; /* 增加图标与文字间距 */
}

/* 4. 上传选项对话框按钮对齐 */
.upload-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 0 20px;
}

.option-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.option-btn .el-icon {
  margin-right: 10px; /* 增加图标与文字间距 */
}

/* 模型图标样式 */
.model-icon {
  font-size: 48px;
  margin-bottom: 15px;
  line-height: 1;
}


/* 对话框样式 */
:deep(.upload-dialog .el-dialog__body) {
  padding: 30px 20px;
}

.upload-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.option-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
}

:deep(.processing-dialog .el-dialog) {
  background-color: transparent;
  box-shadow: none;
}

.processing-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
}

.processing-content p {
  margin-top: 10px;
  color: #4caf50;
}

.model-icon {
  font-size: 48px;
  margin-bottom: 15px;
}


@media (max-width: 768px) {
  .model-content {
    padding: 15px 5px;
  }

  .image-container {
    min-height: 250px;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 10px 10px 70px;
  }

  .model-card {
    margin-bottom: 12px;
  }

  .quick-actions {
    flex-direction: column;
    gap: 12px;
  }

  .quick-actions .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style>